<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    div {
        text-align: center;
    }

    div>img {
        /* 清空上下间距 */
        vertical-align: top;
    }

    #main>img {
        margin-top: 10px;
    }

    div.fix {
        position: fixed;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
    }
</style>

<body>
    <div id="top">
        <img src="./imgs/top.png" alt="">
    </div>
    <div id="nav">
        <img src="./imgs/nav.png" alt="">
    </div>
    <div id="main">
        <img src="./imgs/main.png" alt="">
    </div>
</body>
<script>
    window.onload = function () {
        var topdiv = document.querySelector('#top')
        var navdiv = document.querySelector('#nav')
        //topdiv的高度
        var heig = topdiv.offsetHeight
        //窗口滚动事件
        window.onscroll = function () {
            // console.log('h=' + heig)
            // console.log(window.pageYOffset)
            //页面滚动高度   window.pageYOffset
            //浏览器兼容
            var scrolly = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop || 0
            if (scrolly >= heig) {
                navdiv.className = 'fix'
            } else {
                navdiv.className = ''
            }
        }
    }
</script>

</html>